// Copyright 2011 Bryan McKelvey, MIT License

/**
 * @fileoverview The Background singleton and the methods available to it
 * @author bryan.mckelvey@gmail.com (McKelvey Bryan)
 */

/**
 * This class interacts with the background page, creating listeners for use
 * with content scripts
 * @constructor
 */
var Content = (function() {
  /**
   * A regular expression used to exclude URLs from having their buttons blocked, so this extension
   * doesn't blow up Facebook or Twitter
   * @const
   * @type {RegExp}
   */
  var WHITELIST_REGEX = /(?:facebook|twitter)\.com\//i;

  /**
   * A comprehensive list of regexes to use against source
   * @const
   * @type Object.<string, RegExp>
   */
  var REGEX_LIST = {
    facebook: /^http:\/\/[a-zA-Z0-9\-\.]*facebook\.com/i,
    twitter: /^http:\/\/[a-zA-Z0-9\-\.]*twitter\.com/i
  };
  
  /**
   * Selections from REGEX_LIST for quick evaluation against source
   * @type Object.<string, RegExp>
   * @see REGEX_LIST
   */
  var regexInUse = {};

  /**
   * Attempts to find a match of the provided string against the regular expressions currently in
   * use, returning true if a match is found and otherwise false
   * @param {string} str The string to evaluate for a match
   * @return {boolean} Whether a match is found
   * @see regexInUse
   * @see setRegex
   */
  function match(str) {
    for (var key in regexInUse) {
      if (str.match(regexInUse[key])) {
        return true;
        break;
      }
    }
    
    return false;
  }
  
  /**
   * Sets the regex in use for quick enumeration and matching against sources
   * @param {Object.<string, string>} settings A list of all settings
   */
  function setRegex(settings) {
    for (var key in settings) {
      if (settings[key] && key in REGEX_LIST) {
        regexInUse[key] = REGEX_LIST[key];
      }
    }
  }
  
  return {
		/**
     * Loads settings, adding a beforeload listener once available to filter IFRAME and SCRIPT
     * garbage. Note that this will not load on Facebook or Twitter pages by design, as that would
     * actually impair a site's functionality.
     */
    load: function() {
      chrome.extension.sendRequest({"type": "options"}, function(response) {
        setRegex(response);
        if (!window.location.href.match(WHITELIST_REGEX)) {
          document.addEventListener("beforeload", function(e) {
            switch(e.target.nodeName) {
              case "IFRAME":
              case "SCRIPT":
                if (match(e.target.src)) {
                  e.preventDefault();
                }
                break;
            }
          }, true);
        }
      });
    }
  }
})();

Content.load();